/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package presentation;

import domain.Agent;
import domain.Debug;
import domain.Game;
import domain.Game.action;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author Isaac
 * This class creates a client which sends messages and recieve the server response
 * the client connect to the server through port 9876
 */

public class Client implements Observer {

    private String      _fileName;
    private int         _numberOfRows;
    private int         _numberOfColumns;

    public Client(){
    }

    public Client(Game game){

        this._fileName  = Game._board.getFileName();
        initializeBoard();
        parse();
    }

    private void initializeBoard() {
        //TODO change constants here:
        _numberOfRows    =     Game._board.getNumberOfRows();
        _numberOfColumns =     Game._board.getNumberOfColumns();
        try {
            sendMessage("Board " + _numberOfColumns + " " + _numberOfRows);
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        }
    }

    private void parse() {
        int row = 0;
        try {
            BufferedReader in = new BufferedReader(new FileReader(_fileName));
            String str;
            while ((str = in.readLine()) != null) {
                process(str, row);
                row++;
            }
            in.close();
        } catch (IOException e) {
            Debug.println(e.getMessage());
        }
    }

    private int cellNumber(int row, int column) {
        return column + 1 + ( row * _numberOfColumns );
    }

    private void process(String str, int row) {

        for (int column=0; column<str.length(); column++){
            try {
                char c = str.charAt(column);
                int square = cellNumber(row, column);
                switch (c) {
                    case ' ':
                        // empty square
                        break;
                    case '#':
                        // wall
                        sendMessage("Walls " + square);
                        break;
                    case 'F':
                        // flag
                        sendMessage("Flags " + square);
                        break;
                    case '.':
                        // icy patch
                    	sendMessage("Icy " + square);
                        break;
                }
            } catch (IOException ex) {
                System.err.println(ex.getMessage());
            }
        }
    }

    /**
     *
     * @return message to be sent
     *
     * This procedure gets a message from the standard input
     */
    public String getCommandMessage(){

            BufferedReader inFromUser =
                    new BufferedReader(new InputStreamReader(System.in));
            String sentence="";
            try {
                    Debug.println("Enter command:");
                    sentence = inFromUser.readLine();
            } catch (IOException e) {
                    Debug.println("Not a command:");
            }
            return sentence;
    }
    /**
     * This procedure send a message to server
     *
     * @param msg
     * @throws IOException
     */
    public void sendMessage(String msg) throws IOException{
            DatagramSocket clientSocket = new DatagramSocket();

            InetAddress IPAddress = InetAddress.getByName("127.0.0.1");

            byte[] sendData = new byte[1024];
            byte[] receiveData = new byte[1024];
            sendData = msg.getBytes();
            DatagramPacket sendPacket =
                    new DatagramPacket(sendData, sendData.length, IPAddress, 9876);

            clientSocket.send(sendPacket);

            DatagramPacket receivePacket =
                    new DatagramPacket(receiveData, receiveData.length);

            clientSocket.receive(receivePacket);

            //String modifiedSentence =
            //        new String(receivePacket.getData());

            //@TODO: uncomment next line:
            //Debug.println("FROM SERVER:" + modifiedSentence);
            clientSocket.close();
    }

    /**
     * This main is to use if the client is used as a stand alone application
     * @param args
     * @throws Exception
     */
    public static void main(String args[]) throws Exception
    {

        Client c = new Client();
        c.sendMessage("Board 18 8");
        c.sendMessage("Agent dan Red East 13");

        String sentence = "";
        sentence = c.getCommandMessage();
        while (sentence.compareTo("exit") != 0){
            c.sendMessage(sentence);
            sentence = c.getCommandMessage();
        }
    }

    public void updateGui(Agent agent, int cell) {
        String agentName 	= agent.getName();
        action act    		= agent.getLastAction();
        String direction 	= "";
        switch (act){
            //TODO change to real directions instead of FWD in all:
            case DOWN : direction = "DOWN" ; break;
            case LEFT : direction = "LEFT" ; break;
            case RIGHT: direction = "RIGHT"; break;
            case UP   : direction = "UP"   ; break;
            case SHOOT: direction = "SHOOT"; break;
        }
        switch (cell)
        {
            case 0:
                try {
                    // send messages to server according to square state:
                	if ( agent.isComingFromIce()){
                		this.sendMessage("MoveAgentFromIce "+ agentName + " " + direction);
                	} else {
                		this.sendMessage("MoveAgent "+ agentName + " " + direction);
                	}
                } catch (IOException ex) {
                    Debug.println(ex.getMessage());
                }
                break;
            case 1:
                try {
                    int cellNumber = cellNumber(agent.getSquare().getRow(), agent.getSquare().getColumn());
                    this.sendMessage("FlagsRemove " + cellNumber);
                    //Debug.println("Enter A KEY to continue");
                    //reader.next();
                } catch (IOException ex) {
                    Debug.println(ex.getMessage());
                }
                break;
            case 2:
                try {
                    int cellNumber = cellNumber(agent.getSquare().getRow(), agent.getSquare().getColumn());
                    this.sendMessage("MakeCamelDead " + cellNumber);
                    //Debug.println("Enter A KEY to continue");
                    //reader.next();
                } catch (IOException ex) {
                    Debug.println(ex.getMessage());
                }
                break;
            default:
                try {
                    this.sendMessage("Agent " + agentName + " BLUE " + direction + " " + cell);
                } catch (IOException ex) {
                    Debug.println(ex.getMessage());
                }
                break;
        }
    }


}
